import {defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import IconsResolver from 'unplugin-icons/resolver'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
import {fileURLToPath, URL} from "node:url";


// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
  const { VITE_BASE_URL, VITE_APP_BASE_API} = loadEnv( mode, process.cwd(), '')
  const IS_PROD = mode === 'production' ;
  const IS_DEV = mode === 'development';
  return {
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
      extensions: ['.vue', '.js', '.json', '.ts']
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [
          ElementPlusResolver(),
          // 自动导入图标组件
          IconsResolver({
            prefix: 'Icon',
          }),
        ],
        imports: ['vue'],
        dts: "./auto-import.d.ts"
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'],
          }),
        ],
        dts: "./components.d.ts"
      }),
    ],
    css: {
      preprocessorOptions: {
        // 全局样式引入
        scss: {
          additionalData: '@import "@/assets/css/theme.scss";',
          javascriptEnabled: true
        }
      }
    },
    // 编译配置
    esbuild: {
      // 生产环境删除 console、debugger 语句
      drop: IS_PROD ? ['debugger', 'console'] : [],
    },
    base: './', // 打包路径
    server: {
      host: '0.0.0.0',
      port: 10086, // 服务端口号
      open: false, // 服务启动时是否自动打开浏览器
      cors: true, // 允许跨域
      proxy: {
        [VITE_APP_BASE_API]: {
          target: VITE_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(VITE_APP_BASE_API, '')
        }
      }
    }
  };
});
